const Controller = require('egg').Controller;

class AlipayController extends Controller {
  async createAlipayOrder() {
    const { ctx } = this;
    const { orderId, paymentMethodType = '' } = ctx.request.body;

    try {
      // Validate order exists and status
      const order = await ctx.service.order.findOne(orderId);
      if (!order) {
        this.ctx.error(500, 'Order not found' )
        return;
      }

      if (order.status_value !== 'wait_pay') {
        this.ctx.error(500, 'Invalid order status' )
        return;
      }

      let orderData = {
        merchantRegion: 'AU',
        env: {
          // clientIp 获取发起者的IP
          clientIp: "127.0.0.1",
        },
        order: {
          buyer: {
            buyerName: {
              fullName: (order.contact_name || '').slice(0,128)
            },
            buyerPhoneNo: (order.contact_phone || '').slice(0,16),
            buyerEmail: (order.contact_email || '').slice(0,64),
          },
          orderAmount: {
            currency: "AUD",
            value: parseInt(order.amount * 100).toString()
          },
          goods: [
            {
              goodsName: `${order.ship.name} - (${order.cycle.start_time}, ${order.cycle.duration}h)`,
              referenceGoodsId: order.cycle.id,
              goodsUnitAmount: {
                currency: "AUD",
                value: parseInt(order.cycle.price * 100).toString()
              },
              goodsQuantity: order.count,
              goodsUrl: `${this.config.antom.clientUrl}/#/order?id=${order.id}`,
            }
          ],
          shipping: {
            shippingName: {
              fullName: (order.contact_name || '').slice(0,128)
            },
            shippingPhoneNo: (order.contact_phone || '').slice(0,16),
            shipToEmail: (order.contact_email || '').slice(0,64),
          },
          orderDescription: order.ship.name,
          referenceOrderId: order.order_no
        },
        paymentAmount: {
          currency: "AUD",
          value: parseInt(order.amount * 100).toString()
        },
        paymentFactor: {
          isAuthorization: true
        },
        paymentMethod: {
          paymentMethodMetaData: {
            paymentMethodRegion: "AUD"
          },
          paymentMethodType: paymentMethodType || "ALIPAY_CN"
        },
        paymentNotifyUrl: `${this.config.antom.clientUrl}/api/payment/alipay/notify`,
        paymentRedirectUrl: `${this.config.antom.clientUrl}/#/payment/success?orderId=` + order.id,
        paymentRequestId: order.order_no, // 商户为识别支付请求而分配的专属 ID。
        productCode: "CASHIER_PAYMENT",
        settlementStrategy: {
          settlementCurrency: "AUD"
        }
      }
      // Create PayPal order
      const result = await ctx.service.alipay.createOrder(orderData);
      if (!result.success) {
        this.ctx.error(500, result.error)
        return;
      }

      // Update order with PayPal order ID
      await ctx.service.order.update(orderId, {
        payment_status: 'created',
        status: 0,
        pay_way: paymentMethodType,
        alipay_create_detail: orderData
      });

      // 返回 PayPal 订单信息
      this.ctx.success(result.data);

    } catch (error) {
      this.ctx.error(500, 'Internal server error' ,error)
      ctx.logger.error('Create PayPal Order Error:', error);
    }
  }
  async notify() {
    const ctx = this.ctx;
    const body = ctx.request.body;
    const result = await ctx.service.alipay.notify(body);
    this.ctx.success(result);
  }

  async refund() {
    const ctx = this.ctx;
    const body = ctx.request.body;
    const result = await ctx.service.alipay.refund(body);
    this.ctx.success(result);
  }
}

module.exports = AlipayController;
